package com.cloudfun.campusshare.configuration.jpa;

import org.hibernate.transform.AliasToBeanResultTransformer;

/**
 * @author wangxiyuan
 * @description
 * @createDate 2021/5/20 10:52
 **/
public class MyAliasToBeanResultTransformer extends AliasToBeanResultTransformer {
    public MyAliasToBeanResultTransformer(Class resultClass) {
        super(resultClass);
    }

    @Override
    public Object transformTuple(Object[] tuple, String[] aliases) {
        for ( int i = 0; i < aliases.length; i++ ) {
            aliases[i] = under2camel(aliases[i]);
        }
        return super.transformTuple(tuple, aliases);
    }

    /**
        功能：下划线命名转驼峰命名
     * 将下划线替换为空格,将字符串根据空格分割成数组,再将每个单词首字母大写
     * @param s
     * @return
     */
    private String under2camel(String s) {
        if(!s.contains("_")){
            return s;
        }
        StringBuffer sb = new StringBuffer();
        s = s.toLowerCase().replace("_", " ");
        String sarr[] = s.split(" ");
        for (int i = 0; i < sarr.length; i++) {
            String w = sarr[i].substring(0, 1).toUpperCase() + sarr[i].substring(1);
            sb.append(w);
        }
        return sb.toString();
    }
}
